import React, { useEffect, useState } from 'react';
import { message } from 'antd';
import { request } from '@/utils/request';
import { getStoredBearerToken, hasStoredToken } from '@/utils/auth';
import { useI18n, toApiLanguageCode } from '@/utils/in18';

interface ImagePreviewModalProps {
    // 图片预览地址（存在时展示弹层）
    url: string | null;
    // 关闭弹层
    onClose: () => void;
}

export const ImagePreviewModal: React.FC<ImagePreviewModalProps> = ({ url, onClose }) => {
    // 打开时禁止背景滚动，关闭时恢复
    useEffect(() => {
        if (url) {
            try {
                document.body.style.overflow = 'hidden';
                document.body.style.touchAction = 'none';
            } catch { }
        }
        return () => {
            try {
                document.body.style.overflow = '';
                document.body.style.touchAction = '';
            } catch { }
        };
    }, [url]);

    if (!url) return null;
    return (
        <div className='fixed inset-0 z-[9000]'>
            <div className='absolute inset-0 bg-black/70' onClick={onClose} />
            <div className='absolute inset-0 flex items-center justify-center p-4'>
                <img src={url} alt='preview' className='max-w-[96vw] max-h-[96vh] object-contain rounded-lg shadow-2xl' />
                <button className='absolute top-4 right-4 text-white text-2xl' onClick={onClose}>×</button>
            </div>
        </div>
    );
};

interface WorkEditPopProps {
    // 选中的作品（存在时展示弹层）
    work: any | null;
    // 关闭弹层
    onClose: () => void;
    // 公开状态变更回调，父组件可用于同步外部列表
    onVisibilityChange?: (workId: number, isPublic: boolean) => void;
    // 删除回调，父组件可用于从外部列表移除该作品
    onDeleted?: (workId: number) => void;
}

export const WorkEditPop: React.FC<WorkEditPopProps> = ({ work, onClose, onVisibilityChange, onDeleted }) => {
    const { locale, t } = useI18n();
    const [messageApi] = message.useMessage();
    const [updatingVisibility, setUpdatingVisibility] = useState<boolean>(false);
    const [deleting, setDeleting] = useState<boolean>(false);
    const [showDeleteConfirm, setShowDeleteConfirm] = useState<boolean>(false);

    // 打开时禁止背景滚动，关闭时恢复
    useEffect(() => {
        if (work) {
            try {
                document.body.style.overflow = 'hidden';
                document.body.style.touchAction = 'none';
            } catch { }
        } else {
            try {
                document.body.style.overflow = '';
                document.body.style.touchAction = '';
            } catch { }
        }
        return () => {
            try {
                document.body.style.overflow = '';
                document.body.style.touchAction = '';
            } catch { }
        };
    }, [work]);

    if (!work) return null;

    // 切换公开/私密
    const handleToggleVisibility = async () => {
        if (!work?.id || updatingVisibility) return;
        const nextPublic = !Boolean(work.is_public);
        const lang = toApiLanguageCode(locale as any);
        const authHeader = getStoredBearerToken();
        if (!authHeader) return;
        setUpdatingVisibility(true);
        try {
            const resp = await request.post('/api/work/updateWorkVisibilityRoute', { work_id: work.id, is_public: nextPublic, language: lang }, { headers: { Authorization: authHeader } });
            if (resp?.data?.success) {
                onVisibilityChange && onVisibilityChange(Number(work.id), nextPublic);
                messageApi.success(nextPublic ? '已设置为公开' : '已设置为私密');
            } else {
                throw new Error('failed');
            }
        } catch (e) {
            messageApi.error('设置失败');
        } finally {
            setUpdatingVisibility(false);
        }
    };

    // 删除作品
    const handleDeleteWork = async () => {
        if (!work?.id || deleting) return;
        const lang = toApiLanguageCode(locale as any);
        const authHeader = getStoredBearerToken();
        if (!authHeader) return;
        setDeleting(true);
        try {
            const resp = await request.post('/api/work/deleteWorkRoute', { work_id: work.id, language: lang }, { headers: { Authorization: authHeader } });
            if (resp?.data?.success) {
                onDeleted && onDeleted(Number(work.id));
            } else {
                messageApi.error('删除失败');
            }
        } catch (e) {
            messageApi.error('删除失败');
        } finally {
            setDeleting(false);
            setShowDeleteConfirm(false);
        }
    };

    return (
        <div style={{ zIndex: 9999 }} className='fixed inset-0 z-[9001]'>
            <div className='absolute inset-0 bg-black/70' onClick={() => { if (!updatingVisibility && !deleting) onClose(); }} />
            <div className='absolute inset-0 flex items-center justify-center p-4'>
                <div className='relative bg-black/20 backdrop-blur rounded-xl p-2 shadow-2xl'>
                    <img src={String(work.image_url || '')} alt='preview_work' className='max-w-[96vw] max-h-[78vh] object-contain rounded-lg shadow-xl' />
                    <button className='absolute top-4 right-4 w-10 h-10 rounded-full bg-black/60 hover:bg-black/70 text-white text-2xl leading-[32px] text-center' onClick={() => { if (!updatingVisibility && !deleting) onClose(); }}>×</button>
                </div>

                {/* 操作区：是否公开 + 删除 */}
                <div className=' absolute w-[80%] justify-around  bottom-6 left-1/2 -translate-x-1/2 flex items-center gap-3 bg-black/60 backdrop-blur px-4 py-2 rounded-full text-white'>
                    <div className='flex items-center gap-2'>
                        <span className='text-sm'>{t('CreatImg.public_label')}</span>
                        <button
                            disabled={updatingVisibility}
                            onClick={handleToggleVisibility}
                            className={`relative w-12 h-6 rounded-full transition-colors ${work.is_public ? 'bg-pink-500' : 'bg-gray-400'}`}
                        >
                            <span className={`absolute top-0.5 transition-all ${work.is_public ? 'left-6' : 'left-0.5'}`}>
                                <span className='block w-5 h-5 bg-white rounded-full'></span>
                            </span>
                        </button>
                    </div>
                    <button
                        disabled={deleting}
                        onClick={() => setShowDeleteConfirm(true)}
                        className='px-3 py-1 rounded-full bg-red-500 hover:bg-red-600 text-sm disabled:opacity-60'
                    >
                        {t('CreatImg.delete')}
                    </button>
                </div>

                {/* 删除确认 */}
                {showDeleteConfirm && (
                    <div className='absolute inset-0 flex items-center justify-center'>
                        <div className='bg-[#1f1f1f] text-white rounded-xl p-4 w-[300px] shadow-2xl border border-[#2a2a2a]'>
                            <div className='font-semibold mb-2'>{t('CreatImg.confirm_delete_title')}</div>
                            <div className='text-xs text-[#cbd0d5] mb-4'>{t('CreatImg.confirm_delete_desc')}</div>
                            <div className='flex justify-end gap-2'>
                                <button className='px-3 py-1 rounded bg-gray-600 hover:bg-gray-500' onClick={() => setShowDeleteConfirm(false)}>{t('CreatImg.cancel')}</button>
                                <button className='px-3 py-1 rounded bg-red-600 hover:bg-red-500 disabled:opacity-60' disabled={deleting} onClick={handleDeleteWork}>{t('CreatImg.confirm')}</button>
                            </div>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};

export default WorkEditPop;


